package com.wanmait.hotelManage.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wanmait.hotelManage.dao.OrderDAO;
import com.wanmait.hotelManage.dao.RegisterDAO;
import com.wanmait.hotelManage.dao.RoomDAO;
import com.wanmait.hotelManage.dao.RoomTypeDAO;
import com.wanmait.hotelManage.util.DBHelper;
import com.wanmait.hotelManage.vo.Order;
import com.wanmait.hotelManage.vo.Pager;
import com.wanmait.hotelManage.vo.Register;
import com.wanmait.hotelManage.vo.Room;
import com.wanmait.hotelManage.vo.RoomType;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/manage/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String action=request.getParameter("action");
		if("init".equals(action)) {
			this.init(request, response);
		}else if("initone".equals(action)) {
			this.initone(request, response);
		}else if("initprice".equals(action)) {
			this.initPrice(request, response);
		}else if("insert".equals(action)) {
			this.insert(request, response);
		}else if("afterinsert".equals(action)) {
			this.afterinsert(request, response);
		}else if("online".equals(action)) {
			this.online(request, response);
		}else if("search".equals(action)) {
			this.search(request, response);
		}else if("roomTypeInsert".equals(action)) {
			this.roomTypeInsert(request, response);
		}else if("insertMultiple".equals(action)) {
			this.insertMultiple(request, response);
		}else if("searchRoomType".equals(action)) {
			this.searchRoomType(request, response);
		}
	}
	protected void searchRoomType(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String roomTypeId = request.getParameter("roomTypeId");
//		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		RoomType findRoomTypeById = RoomTypeDAO.getRoomtypedao().findRoomTypeById(Integer.parseInt(roomTypeId));
		String roomType=findRoomTypeById.getTitle();
		System.out.println(roomTypeId);
//		System.out.println(startTime);
		System.out.println(endTime);
		Date st=new Date();
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//		Date st=null;
		Date et=null;
		try {
//			st=dateFormat.parse(startTime);
			et=dateFormat.parse(endTime);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		Timestamp tst=new Timestamp(st.getTime());
		Timestamp tet=new Timestamp(et.getTime());
		//获得入住的每一天
		List<Timestamp> timestamps=new ArrayList<Timestamp>();
		while(true) {
			if(tst.before(tet)) {
				timestamps.add(tst);
				Calendar startCalendar = Calendar.getInstance();
				startCalendar.setTime(tst);
				startCalendar.add(startCalendar.DATE, 1);
				tst = new Timestamp(startCalendar.getTimeInMillis());
				
			}else {
				break;
			}
		}
		//判断房间类型
		if("房间类型".equals(roomType)) {//搜索全部的房间类型
			//获得全部房间类型
			List<RoomType> allroomTypes=(List<RoomType>)RoomTypeDAO.getRoomtypedao().findAll();
			Pager pager = new Pager();
			pager.setPageSize(2);//每页显示的记录数
			int rows = RoomTypeDAO.getRoomtypedao().getSearchRows(allroomTypes,timestamps);//总行数
			pager.setPageCount(rows);//总页数
			pager.setPageNo(1);//默认显示第一页
			//获得符合条件的房间类型
			List<RoomType> roomTypes=RoomTypeDAO.getRoomtypedao().search(allroomTypes,timestamps,pager);
		
//			request.setAttribute("startTime", startTime);
			request.setAttribute("endTime", endTime);
			request.setAttribute("pager",pager);
			request.setAttribute("roomTypes", roomTypes);
			request.getRequestDispatcher("/FrontDesk/searchRoomList.jsp").forward(request, response);
		}else {//指定房间类型搜索
			Boolean flag=RoomTypeDAO.getRoomtypedao().search(roomType,timestamps);
			System.out.println(flag);
			if(flag) {//有空房
				response.setCharacterEncoding("utf-8");
				roomType = URLEncoder.encode(roomType);
				List<Room> rooms = RoomDAO.getRoomdao().findByroomTypeId(Integer.parseInt(roomTypeId));
//				request.setAttribute("startTime", startTime);
				request.setAttribute("endTime", endTime);
				
				request.setAttribute("rooms", rooms);
				request.getRequestDispatcher("/manage/register/initOne.jsp").forward(request, response);
//				request.getRequestDispatcher("/roomListServlet?action=roomDetail&roomTypeName="+roomType).forward(request, response);
			}else {//没空房
				response.setCharacterEncoding("utf-8");
				roomType = URLEncoder.encode(roomType);
//				request.setAttribute("startTime", startTime);
				request.setAttribute("endTime", endTime);
				request.setAttribute("msg", "no");
//				request.getRequestDispatcher("/roomListServlet?action=roomDetail&roomTypeName="+roomType).forward(request, response);
		}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	/**
	 * 订单表里的数据对方形表里的数据进行添加
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void roomTypeInsert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer roomTypeId=Integer.parseInt(request.getParameter("number"));
		String name=request.getParameter("name");
		String telephone=request.getParameter("telephone");
		String gender=request.getParameter("gender");
		String breakfast=request.getParameter("breakfast");
		String idCard=request.getParameter("idCard");
		String endTime=request.getParameter("endTime");
		endTime=endTime+=" 12:00:00";
		Boolean flag=false;
		Boolean flag1=false;
		if("男".equals(gender)) {
			flag=true;
		}
		if("需要".equals(breakfast)) {
			flag1=true;
		}
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Timestamp endtime=null;
		try {
			 endtime=new Timestamp(df.parse(endTime).getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Register register=new Register();
		register.setName(name);
		register.setTelephoneNumber(telephone);
		register.setEndTime(endtime);
		register.setIdCard(idCard);
			register.setGender(flag);
			register.setBreakfast(flag1);
			Room room=new Room();
			room.setId(roomTypeId);
			register.setRoom(room);
			register.setDeposit(100.0);
			RegisterDAO.getRegisterdao().insert(register);
			RoomDAO.getRoomdao().updateCheckIn(register);
			OrderDAO.getOrderdao().updateReg(register);
			response.sendRedirect(request.getContextPath()+"/manage/RegisterServlet?action=online");
	}
	/**
	 * 网上预约搜索，搜索到就添加数据，搜索不到返回网上预约窗口
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String findName=request.getParameter("findName");
	String findTelephone=request.getParameter("findTelephone");
	Order orders=OrderDAO.getOrderdao().SearchByNameAndTelephone(findName,findTelephone);
	if(orders!=null) {
		request.setAttribute("orders", orders);
		List<RoomType>roomTypes=RoomTypeDAO.getRoomtypedao().findAll();
//		RoomType roomtype=RoomTypeDAO.getRoomtypedao().findRoomTypeById(orders.getRoomType().getId());
//		request.setAttribute("roomtype", roomtype);
		List<Room> rooms=RoomDAO.getRoomdao().findRoomByRoomTypeId(orders.getRoomType().getId());
		
		request.setAttribute("rooms", rooms);
		request.setAttribute("roomTypes", roomTypes);
		request.getRequestDispatcher("/manage/register/onlinePredestineTwo.jsp").forward(request, response);
		return;
	}else if(orders==null) {
		response.sendRedirect(request.getContextPath()+"/manage/RegisterServlet?action=online&msg=no");
	}
	}
	/**
	 * 网上预约的初始化
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void online(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<RoomType>roomTypes=RoomTypeDAO.getRoomtypedao().findAll();
		request.setAttribute("roomTypes", roomTypes);
		request.getRequestDispatcher("/manage/register/onlinePredestine.jsp").forward(request, response);
	}
	/**
	 * 没用到，但不想删
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void afterinsert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer roomTypeId=Integer.parseInt(request.getParameter("number"));
		System.out.println(roomTypeId);
		String name=request.getParameter("name");
		String telephone=request.getParameter("telephone");
		String gender=request.getParameter("gender");
		String breakfast=request.getParameter("breakfast");
		String idCard=request.getParameter("idCard");
		String startTime=request.getParameter("startTime");
		String endTime=request.getParameter("endTime");
		Boolean flag=false;
		Boolean flag1=false;
		if("男".equals(gender)) {
			flag=true;
		}
		if("需要".equals(breakfast)) {
			flag1=true;
		}
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Timestamp starttime=null;
		Timestamp endtime=null;
		try {
			 starttime=new Timestamp(df.parse(startTime).getTime());
			 endtime=new Timestamp(df.parse(endTime).getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
			Register register=new Register();
			register.setName(name);
			register.setTelephoneNumber(telephone);
			register.setStartTime(starttime);
			register.setEndTime(endtime);
			register.setIdCard(idCard);
			register.setGender(flag);
			register.setBreakfast(flag1);
			Room room=new Room();
			room.setId(roomTypeId);
			register.setRoom(room);
			register.setDeposit(100.0);
			RegisterDAO.getRegisterdao().insert(register);
			List<RoomType>roomTypes=RoomTypeDAO.getRoomtypedao().findAll();
			request.setAttribute("roomTypes", roomTypes);
			request.setAttribute("register", register);
			request.getRequestDispatcher("/manage/register/siteAddTwo.jsp").forward(request,response);
//			response.sendRedirect(request.getContextPath()+"/manage/RegisterServlet?action=secondinit");
	}
	/**
	 * 网上预约添加多个客人
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer number=Integer.parseInt(request.getParameter("number"));
		String[] name=request.getParameterValues("name");
		String[] telephone=request.getParameterValues("telephone");
		String[] gender=request.getParameterValues("gender");
		String breakfast=request.getParameter("breakfast");
		String[] idCard=request.getParameterValues("idCard");
		String endTime=request.getParameter("endTime");
		endTime=endTime+=" 12:00:00";
		Boolean flag=false;
		Boolean flag1=false;
		
		
		if("需要".equals(breakfast)) {
			flag1=true;
		}
		DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Timestamp starttime=null;
		Timestamp endtime=null;
		try {
			 endtime=new Timestamp(df.parse(endTime).getTime());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (int i = 0; i < name.length; i++) {
			if("男".equals(gender[i])) {
				flag=true;
			}
			Register register=new Register();
			register.setName(name[i]);
			register.setTelephoneNumber(telephone[i]);
			register.setEndTime(endtime);
			register.setIdCard(idCard[i]);
			register.setGender(flag);
			register.setBreakfast(flag1);
			Room room=new Room();
			Integer id=RoomDAO.getRoomdao().findbyNumber(number+"");
			room.setId(id);
////		String number=RoomDAO.getRoomdao().findbynumber(roomId);
			room.setNumber(number+"");
			register.setRoom(room);
			register.setDeposit(100.0);
			Boolean flag11=RegisterDAO.getRegisterdao().booleanRegister(register);
//			if(flag11) {
//				response.sendRedirect(request.getContextPath()+"/manage/RegisterServlet?action=online");
//				return;
//			}else {
			RegisterDAO.getRegisterdao().insert(register);
			RoomDAO.getRoomdao().updateCheckIn(register);
			if(i==0) {
				OrderDAO.getOrderdao().updateReg(register);
			}
//	}
		}
		response.sendRedirect(request.getContextPath()+"/manage/RegisterServlet?action=online");
	}
	/**
	 * 线上预约多个客人添加
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void insertMultiple(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			Integer roomId=Integer.parseInt(request.getParameter("number"));
			System.out.println(roomId);
			String[] name=request.getParameterValues("name");
			String[] telephone=request.getParameterValues("telephone");
			String gender=request.getParameter("gender");
			String breakfast=request.getParameter("breakfast");
			String[] idCard=request.getParameterValues("idCard");
			String endTime=request.getParameter("endTime");
			endTime=endTime+=" 12:00:00";
			Boolean flag=false;
			Boolean flag1=false;
			if("男".equals(gender)) {
				flag=true;
			}
			if("需要".equals(breakfast)) {
				flag1=true;
			}
			DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Timestamp endtime=null;
			try {
				 endtime=new Timestamp(df.parse(endTime).getTime());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			for (int i = 0; i < name.length; i++) {
				Register register=new Register();
				register.setName(name[i]);
				register.setTelephoneNumber(telephone[i]);
				register.setEndTime(endtime);
				register.setIdCard(idCard[i]);
				register.setGender(flag);
				register.setBreakfast(flag1);
				Room room=new Room();
				room.setId(roomId);
				System.out.println(roomId);
				String number=RoomDAO.getRoomdao().findbynumber(roomId);
				room.setNumber(number);
				System.out.println(number);
				register.setRoom(room);
				register.setDeposit(100.0);
				Boolean flag11=RegisterDAO.getRegisterdao().booleanRegister(register);
//				if(flag11) {
//					response.sendRedirect(request.getContextPath()+"/manage/RegisterServlet?action=init");
//					return;
//				}else {
				RegisterDAO.getRegisterdao().insert(register);
				RoomDAO.getRoomdao().updateCheckIn(register);
//				}
			}
				response.sendRedirect(request.getContextPath()+"/manage/RegisterServlet?action=init");
		}
	/**
	 * AJAX更改价钱
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void initPrice(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer id=Integer.parseInt(request.getParameter("id"));
		RoomType roomtype=RoomTypeDAO.getRoomtypedao().findprice(id);
		PrintWriter pw=response.getWriter();
		Double price=roomtype.getDiscountPrice();
		pw.print(price);
//		request.setAttribute("roomtype", roomtype);
//		request.getRequestDispatcher("/manage/register/siteAdd.jsp").forward(request, response);
	}
	/**
	 * AJAX的房间编号输出
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void initone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer id=Integer.parseInt(request.getParameter("id"));
//		System.out.println(id);
		List<Room>rooms=RoomDAO.getRoomdao().findByroomTypeId(id);
		request.setAttribute("rooms", rooms);
		request.getRequestDispatcher("/manage/register/initOne.jsp").forward(request, response);
	}
	/**
	 * 线上预约的初始化
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void init(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	List<RoomType>roomTypes=RoomTypeDAO.getRoomtypedao().findAll();
	//RoomTypeDAO.getRoomtypedao().
	request.setAttribute("roomTypes", roomTypes);
	request.getRequestDispatcher("/manage/register/siteAdd.jsp").forward(request, response);
	}
}
